import 'dart:io';

import 'package:dio/dio.dart';

import '../constants.dart';
import '../utils/sp_utils.dart';

class CookieInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    // 从本地获取cookie
    Object cookies = SpUtils.getStringList(Constants.COOKIE_LIST);
    options.headers[HttpHeaders.cookieHeader] = cookies;
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    if(response.requestOptions.path == 'user/login') {
      dynamic list = response.headers[HttpHeaders.setCookieHeader];
      List<String> cookies = [];
      if (list is List) {
        cookies = list.map((e) => e as String).toList();
      }
      // 登录成功后，将cookie存储到本地
      SpUtils.putStringList(Constants.COOKIE_LIST, cookies);
    }
    super.onResponse(response, handler);
  }
}